package org.goldfish.chatroom.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.goldfish.chatroom.entity.VerificationMessage;
import org.jetbrains.annotations.NotNull;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface VerificationMessageMapper {
    List<VerificationMessage> getVerificationMessageList();


    void insertVerificationMessage(VerificationMessage verificationMessage);

    VerificationMessage getExistingLatestVerificationMessage();

    void deleteStaleMessages(VerificationMessage latest);

    @NotNull
    default VerificationMessage getLatestVerificationMessage(boolean refresh) {
        int delay_secs = 5 * 60;
        VerificationMessage verificationMessage = null;
        try {
            verificationMessage = getExistingLatestVerificationMessage();
        } catch (RuntimeException ignore) {
        }
        // now that existing latest message is read out,
        // we can compare the time now to see
        // if the latest message is still valid
        LocalDateTime dateTime = LocalDateTime.now();

        // procedures for an empty query result: generate a new verification message
        if (verificationMessage == null) {
            VerificationMessage newMessage = new VerificationMessage();
            insertVerificationMessage(newMessage);
            try {
                deleteStaleMessages(newMessage);
            } catch (RuntimeException ignore) {
            }
            return newMessage;
        }

        // procedures for an outdated latest message: generate a new verification message
        if (refresh || dateTime.minusSeconds(delay_secs).isAfter(verificationMessage.getTime())) {
            VerificationMessage newMessage = new VerificationMessage();
            insertVerificationMessage(newMessage);
            try {
                deleteStaleMessages(newMessage);
            } catch (RuntimeException ignore) {
            }
            return newMessage;
        }
        // procedures for a valid latest message: return the latest message
        return verificationMessage;
    }
}
